package com.example.myspringframework.context.support;

import cn.hutool.core.bean.BeanException;
import com.example.myspringframework.beans.BeansException;
import com.example.myspringframework.beans.factory.ConfigurableListableBeanFactory;
import com.example.myspringframework.beans.factory.config.BeanDefinition;
import com.example.myspringframework.beans.factory.config.BeanFactoryPostProcessor;
import com.example.myspringframework.beans.factory.config.BeanPostProcessor;
import com.example.myspringframework.beans.factory.support.DefaultListableBeanFactory;
import com.example.myspringframework.context.ApplicationEvent;
import com.example.myspringframework.context.ApplicationListener;
import com.example.myspringframework.context.ConfigurableApplicationContext;
import com.example.myspringframework.context.event.ApplicationEventMulticaster;
import com.example.myspringframework.context.event.ContextClosedEvent;
import com.example.myspringframework.context.event.ContextRefreshedEvent;
import com.example.myspringframework.context.event.SimpleApplicationEventMulticaster;
import com.example.myspringframework.core.convert.ConversionService;
import com.example.myspringframework.core.io.DefaultResourceLoader;

import java.util.Collection;
import java.util.Map;

/**
 * 主要对refresh方法进行实现，主要是BeanFactoryPostProcessor和BeanPostProcessor的自动注册和执行
 */
public abstract class AbstractApplicationContext extends DefaultResourceLoader implements ConfigurableApplicationContext {

    public static final String APPLICATION_EVENT_MULTICASTER_BEAN_NAME = "applicationEventMulticaster";
    private ApplicationEventMulticaster applicationEventMulticaster;

    @Override
    public void refresh() throws BeanException {
        // 创建BeanFactory并加载BeanDefiniton
        refreshBeanFactory();

        // 获取第一步创建的BeanFactory
        ConfigurableListableBeanFactory beanFactory = this.getBeanFactory();

        //添加ApplicationContextAwareProcessor，让继承自ApplicationContextAware的bean能感知bean
        beanFactory.addBeanPostProcessor(new ApplicationContextAwareProcessor(this));

        // 执行BeanFactoryPostProcessor
        invokeBeanFactoryPostProcessors(beanFactory);

        // 注册BeanPostProcessor到容器
        registerBeanPostProcessors(beanFactory);

        // 初始化事件发布器
        initApplicationEventMulticaster();

        //注册事件监听器
        registerListeners();

        // 设置类型转换器并提前实例化bean
        finishBeanFactoryInitialization(beanFactory);

        // 发布容器刷新完成事件
        finishRefresh();
    }

    private void finishRefresh() {
        this.publishEvent(new ContextRefreshedEvent(this));
    }

    @Override
    public void publishEvent(ApplicationEvent event) {
        this.applicationEventMulticaster.multicastEvent(event);
    }

    /**
     * 注册监听器
     */
    private void registerListeners() {
        Collection<ApplicationListener> applicationListeners = this.getBeansOfType(ApplicationListener.class).values();
        for (ApplicationListener applicationListener : applicationListeners) {
            this.applicationEventMulticaster.addApplicationListener(applicationListener);
        }
    }

    /**
     * 初始化事件发布器
     */
    private void initApplicationEventMulticaster() {
        ConfigurableListableBeanFactory beanFactory = this.getBeanFactory();
        this.applicationEventMulticaster = new SimpleApplicationEventMulticaster();
        beanFactory.addSingleton(APPLICATION_EVENT_MULTICASTER_BEAN_NAME, this.applicationEventMulticaster);
    }

    public abstract ConfigurableListableBeanFactory getBeanFactory();

    /**
     * 创建BeanFactory并加载BeanDefiniton
     *
     * @throws BeanException
     */
    protected abstract void refreshBeanFactory() throws BeanException;

    /**
     * 执行BeanFactoryPostProcessor中的方法
     *
     * @param beanFactory
     */
    private void invokeBeanFactoryPostProcessors(ConfigurableListableBeanFactory beanFactory) {
        Map<String, BeanFactoryPostProcessor> beanFactoryPostProcessors = beanFactory.getBeansOfType(BeanFactoryPostProcessor.class);
        for (BeanFactoryPostProcessor beanFactoryPostProcessor : beanFactoryPostProcessors.values()) {
            beanFactoryPostProcessor.postProcessBeanFactory(beanFactory);
        }
    }

    /**
     * 注册BeanPostProcessor
     *
     * @param beanFactory
     */
    private void registerBeanPostProcessors(ConfigurableListableBeanFactory beanFactory) {
        Map<String, BeanPostProcessor> beanPostProcessorMap = beanFactory.getBeansOfType(BeanPostProcessor.class);
        for (BeanPostProcessor beanPostProcessor : beanPostProcessorMap.values()) {
            beanFactory.addBeanPostProcessor(beanPostProcessor);
        }
    }

    @Override
    public Object getBean(String beanName) throws BeansException {
        return this.getBeanFactory().getBean(beanName);
    }

    @Override
    public <T> T getBean(String beanName, Class<T> requiredType) throws BeansException {
        return this.getBeanFactory().getBean(beanName, requiredType);
    }

    @Override
    public <T> T getBean(Class<T> requiredType) throws BeansException {
        return this.getBeanFactory().getBean(requiredType);
    }

    @Override
    public <T> Map<String, T> getBeansOfType(Class<T> type) throws BeansException {
        return this.getBeanFactory().getBeansOfType(type);
    }

    @Override
    public String[] getBeanDefinitionNames() {
        return this.getBeanFactory().getBeanDefinitionNames();
    }

    /**
     * 提供给外部手动调用关闭方法
     */
    @Override
    public void close() {
        this.doClose();
    }

    /**
     * 向虚拟机中注册钩子函数
     */
    @Override
    public void registerShutdownHook() {
        Thread shutdownHook = new Thread(this::doClose);
        Runtime.getRuntime().addShutdownHook(shutdownHook);
    }

    @Override
    public boolean containsBean(String beanName) {
        return this.getBeanFactory().containsBean(beanName);
    }

    protected void doClose() {
        // 发布容器关闭事件
        this.publishEvent(new ContextClosedEvent(this));
        // 执行单例bean销毁方法
        this.destroyBeans();
    }

    protected void destroyBeans() {
        this.getBeanFactory().destroySingletons();
    }

    protected void finishBeanFactoryInitialization(ConfigurableListableBeanFactory beanFactory){
        // 注册类型转换器
//        ConversionService conversionService = beanFactory.getBean(ConversionService.class);
        if (beanFactory.containsBean("conversionService")){
            Object bean = beanFactory.getBean("conversionService");
            if (bean instanceof ConversionService conversionService){
                beanFactory.setConversionService(conversionService);
            }
        }
        // 提前实例化单例bean
        beanFactory.preInstantiateSingletons();
    }

}
